package com.blueberriesteam.kg.parser;

import android.annotation.TargetApi;
import android.os.Build;
import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.DomSerializer;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Denis on 07.09.13.
 */
public  class Connect {

    private static String link;




    @TargetApi(Build.VERSION_CODES.FROYO)
    public static NodeList getPage(String queries){

        Document document;
        NodeList pageNode = null;
        try {
            URL url = new URL(link);
            TagNode tagNode = new HtmlCleaner().clean(url);
            document = new DomSerializer(new CleanerProperties()).createDOM(tagNode);
            XPath xPath = XPathFactory.newInstance().newXPath();
            pageNode = (NodeList)xPath.evaluate(queries,document, XPathConstants.NODESET);
        }catch (MalformedURLException exc){
            exc.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }catch (ParserConfigurationException e){
            e.printStackTrace();
        }catch (XPathExpressionException e){
            e.printStackTrace();
        }
        return pageNode;

    }


    public static void setLink(String link) {
        Connect.link = link;
    }
}
